package com.sh.ssao.lottery.config.utils;

import java.util.*;

/**
 * 树生成
 */
public class MenuUtils {

    public static Map<String,List<Map<String,Object>>> cleanData(List<Map<String,Object>> ld,int loop){
        Map<String,List<Map<String,Object>>> map = new HashMap();//存储整理数据
        for (int i = 1; i <= loop; i++) {
            //分层整理数据
            List<Map<String,Object>> layer = new ArrayList();
            for (Map m:ld) {
                if (m.containsKey("leve") && m.get("leve").equals(i)) {
                    layer.add(m);
                }
            }
            map.put("list_"+i,layer);
        }
        return map;
    }

    /**
     * 无限极级目录
     * @param ld
     * @return
     */
    public static List<Map<String,Object>> menuFactory(List<Map<String,Object>> ld,int loop){
        Map<String,List<Map<String,Object>>> map = cleanData(ld,loop);//1，数据整理
        try{
            List<Map<String,Object>> node = map.get("list_"+loop);//2,获取最底层子节点
            for (int i = loop-1; i > 0; i--) {
                List<Map<String,Object>> pnode = map.get("list_"+i);//3,获取步骤2父节点
                for (Map<String,Object> po:pnode) {
                    List<Map<String,Object>> tempnode = new ArrayList();//创建子节点临时存储器
                    for (Map<String,Object> no:node) {
                        if (po.containsKey("id") && po.get("id").equals(no.get("pid"))) {//针对layui树插件
                            tempnode.add(no);//组合子节点集合
                        }else if (po.containsKey("value") && po.get("value").equals(no.get("pid"))){//针对xm-select下拉框多选树插件
                            if (no.containsKey("selected") && "true".equals(no.get("selected"))){
                                no.put("selected",true);
                            }else if(no.containsKey("selected") && "false".equals(no.get("selected"))){
                                no.put("selected",false);
                            }
                            //是否展开
                            if (no.containsKey("spread") && "0".equals(no.get("spread"))){
                                no.put("spread",true);
                            }else if(no.containsKey("spread") && "1".equals(no.get("spread"))){
                                no.put("spread",false);
                            }

                            tempnode.add(no);//组合子节点集合
                        }
                    }
                    //将子节点集合组合到父节点下
                    po.put("children",tempnode);
//                   System.out.println("1.将子节点集合组合到父节点下:"+po.toString());
                }
                //将组装好的数据赋值到当前父节点层，作为下一次循环子节点
//              System.out.println("2.将组装好的数据赋值到当前父节点层，作为下一次循环子节点:"+pnode);
                node = pnode;
            }
            return node;
        }catch(Exception e){
            return null;
        }
    }

}
